<?php
namespace app\api\controller;

use think\Session;
use think\Request;
use app\index\model\User;
use think\controller\Rest;
use app\common\tools\Tool;
use app\common\tools\ID as IDObj;

class Comment extends Rest{
  
  public function rest(){
        switch ($this->method){
      case 'get':   //查询
        $this->read($id);
        break;
      case 'post':  //新增
        $this->add();
        break;
      case 'put':   //修改
        $this->update($id);
        break;
      case 'delete':  //删除
        $this->delete($id);
        break;
      
        }
    }

    public function read(){
        if(!Session::get('guest')){
            // 创建访客用户
            $idobj = new IDObj();
            $uid = $idobj->getUID();
            $usrn = 'guest_'.$uid;
            $ip = Tool::getRealIpAddr();
            $city = Tool::getCity();
            // 保存随机头像
            $rand = mt_rand(100,299);
            $picUrl = "https://cdn.v2ex.com/gravatar/594f0e38ee46673f7ab6ee9b15{$rand}dd?d=identicon";
            $sql = "INSERT into sinblog_guest_list (uid,user_name,profile_pic,visit_time,ip,addr) values('{$uid}','{$usrn}','{$picUrl}',unix_timestamp(now()),'{$ip}','{$city}');";
            $guestObj = new User;
            $guestObj->query($sql);
            $lastId = $guestObj->getLastInsID();
            $res = $guestObj->query("select * from sinblog_guest_list where id = '{$lastId}'");
            Session::set('guest',$res);
        }
      $aid = input('param.aid');
      $model = model('Comment');
      $data=$model->where('aid',$aid)->where('state',0)->where('parent_id',0)->order('created')->select();// 查询单个数据
      // 处理子评论
      for ($i=0; $i < count($data); $i++) { 
          $cmt = $data[$i];
          $data[$i]['subcmts'] = $model->where('state',0)->where('parent_id',$cmt['id'])->order('created')->select();
      }

      return json($data);
    }

  
    public function add(){
        $model = model('Comment');
        $param=Request::instance()->param();
        // 获取当前请求的所有变量（经过过滤）
        // 添加其他所需信息
        $user = '';
        if (Session::get('user')) {
            $user = Session::get('user');
        }else{
            // 获取临时用户信息
            $user = Session::get('guest')[0];
        }

        $param['aid'] = input('param.aid');
        $param['pic'] = $user['profile_pic'];
        $param['uid'] = $user['uid'];
        $param['text'] = htmlentities($param['text'],ENT_QUOTES,'UTF-8');
        // $param['name'] = $user['user_name'];
        if($model->save($param)){
        $cmtid = $model->getLastInsID();
        $cmt =  $model->where('id',$cmtid)->find();
        return $cmt;
          return json(["status"=>1]);
        }else{
          return json(["status"=>0]);
        }
    }


    public function update($id){
        $model = model('Comment');
        $param=Request::instance()->param();
        if($model->where("id",$id)->update($param)){
          return json(["status"=>1]);
        }else{
          return json(["status"=>0]);
        }
    }


    public function delete($id){
      
        $model = model('Comment');
        $rs=$model::get($id)->delete();
        if($rs){
          return json(["status"=>1]);
        }else{
          return json(["status"=>0]);
        }
    }
}


/*

CREATE TABLE IF NOT EXISTS `sinblog_guest_list` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `uid` char(16) NOT NULL,
  `user_name` varchar(10) NOT NULL,
  `profile_pic` char(100) NOT NULL,
  `addr` varchar(30) DEFAULT '中国' COMMENT '上次登录地',
  `ip` char(15) NOT NULL DEFAULT '000.000.000.000' COMMENT '上次登录的ip',
  `visit_time` int(10) DEFAULT NULL COMMENT '上次登录时间戳',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

*/